<!--组件：密级选择器-->
<template>
  <a-select
    v-model="selected"
    :allow-clear="allowClear"
    :disabled="disabled"
    :options="options"
    placeholder="请选择密级"
    :loading="loading"
    style="width: 100%"
    :popup-container="isFullscreen ? mainBox : 'body'"
    @change="handleChange"
  />
</template>

<script setup lang="ts">
  import { onMounted, ref, watch, computed } from 'vue';
  import { warning } from '@/common/utils/modal-promise';
  import { queryDictDataRecordList } from '@/api/system/dictionary';
  import { useAppStore, useUserStore } from '@/store';
  import { isFullscreen } from '@/common/hooks/full-screen';

  const props = defineProps({
    defaultValue: { type: String, default: '' },
    allowClear: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
    secretLevel: { type: Number || String, default: undefined },
    isShowClearTip: { type: Boolean, default: false },
    dictType: { type: String, default: 'secretLevel' },
  });
  const emits = defineEmits(['change', 'update:modelValue']);
  const mainBox = ref();
  mainBox.value = document.querySelector('main');
  watch(
    () => props.defaultValue,
    () => {
      selected.value = props.defaultValue;
    }
  );
  watch(
    () => props.secretLevel,
    () => {
      fetchOptions();
    },
    {
      deep: true,
    }
  );

  const appStore = useAppStore();
  const userStore = useUserStore();
  const secretLevel = computed(() => appStore.secretLevel);
  const userSecretLevel = computed(() => userStore.secretLevel || 4);

  const validateSecret = (level: string) => {
    // 校验密级是否满足条件：
    // 1密级应小于用户本身的密级
    // 2密级应小于系统密级
    // 3密级小于传入值
    if (parseInt(level, 10) <= secretLevel.value) {
      if (props.secretLevel) {
        return (
          parseInt(level, 10) <= userSecretLevel.value &&
          parseInt(level, 10) <= Number(props.secretLevel)
        );
      }
      return parseInt(level, 10) <= userSecretLevel.value;
    }
    return false;
  };

  const selected = ref<string>(props.defaultValue);
  const loading = ref<boolean>(false);

  const options = ref<{ label: string; value: string }[]>([]);
  const fetchOptions = async () => {
    try {
      const { data } = await queryDictDataRecordList({
        dictType: props.dictType,
      });
      const list: { label: string; value: string }[] = [];
      data.forEach(({ label, value }) => {
        if (label && value && validateSecret(value)) {
          list.push({ label, value });
        }
      });
      options.value = list;
    } finally {
      loading.value = false;
    }
  };
  onMounted(() => {
    fetchOptions();
  });
  const handleChange = async (value: string | number | Record<string, any>) => {
    if (props.isShowClearTip && props.defaultValue) {
      try {
        await warning({
          title: '提示',
          content: '变更密级会清除和密级相关的选择项，是否继续！',
          hideCancel: false,
        });
      } catch (e) {
        emits('update:modelValue', props.defaultValue);
        return;
      }
    }
    emits(
      'change',
      value,
      options.value.find((i) => i.value === value)
    );
    emits('update:modelValue', value);
  };
</script>
